package com.android.demp;

import java.util.Random;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AlphabetIndexer;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.Toast;



public class VocDemo extends ListActivity {
    private Cursor myCursor;
	private CursorAdapter mAdapter;
	public static final String PREFS_NAME = "MyPrefsFile";
	static final boolean CREATE_DB = false;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_speakers_content);
        // Restore preferences
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        boolean Db = settings.getBoolean("CreateDatabase", true);
        connectToDb(Db);
    }
    @Override
    protected void onStop(){
       super.onStop();

      // We need an Editor object to make preference changes.
      // All objects are from android.context.Context
      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("CreateDatabase", CREATE_DB);

      // Commit the edits!
      editor.commit();
    }
    
    public void connectToDb(boolean Db){
    	
        doNotKnowDBAdapter ad = new doNotKnowDBAdapter(this);
		ad.open();
    	if(Db == true)
    	{
			doNotKnowColumn cols = new doNotKnowColumn();
			StringBuffer buf=new StringBuffer(128);
			for(int i=65; i<= 90;i++)buf.append((char)i); // A-Z
			char []alphanumeric=buf.toString().toCharArray();
			Random rand=new Random();
			for(int i=0;i<26;i++)
			{
				for(int k=0;k<10;k++)
				{	
					StringBuffer out=new StringBuffer();
					while(out.length() < 10){
						int idx=Math.abs(( rand.nextInt() % alphanumeric.length ));
						out.append(alphanumeric[idx]);
					}
					cols.setWord(out.toString());
					cols.setShortMeaning("My meaning " + out.toString());
					cols.setExplain("My Explaim " + out.toString());
					cols.setImagePath("Image " + out.toString());
					cols.setGrammar("Verb " + out.toString());
					ad.insertEntry(cols);	
				}
			}
    		Toast toast = Toast.makeText(getApplicationContext(), "Create Database",Toast.LENGTH_LONG);
    		toast.show();
    	}
    	else
    	{
    		Toast toast = Toast.makeText(getApplicationContext(), "Database Already Created",Toast.LENGTH_LONG);
    		toast.show();
    	}
    	myCursor = ad.getAllEntries();
		//startManagingCursor(myCursor);
		mAdapter=new MyCursorAdapter(this,myCursor);
		setListAdapter(mAdapter) ;// to
		final PinnedHeaderListView list = (PinnedHeaderListView) getListView();
		View pinnedHeader = getLayoutInflater().inflate(R.layout.list_item_header, list, false);
		list.setPinnedHeaderView(pinnedHeader);
		list.setDividerHeight(0);
		list.setOnScrollListener((MyCursorAdapter) mAdapter);
		list.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View view,
						int arg2, long arg3) {
					Intent myIntent = new Intent(getApplicationContext(), Detail.class);
                    startActivity(myIntent);
					
				}
	          });
		
		//mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);
        //mHandler.startQuery(0, DBAdapter.KEY_WORD, new String[]{DBAdapter.KEY_WORD+" ASC"});
    }

	/** {@inheritDoc} */
    public void onQueryComplete(int token, Object cookie, Cursor cursor) {
        //startManagingCursor(myCursor);
        mAdapter.changeCursor(myCursor);
    }
    private abstract class BaseAdapter extends CursorAdapter {

		public BaseAdapter(Context context, Cursor cursor) {
			super(context, myCursor, true);
		}
    	
	    protected void findAndCacheViews(View view) {
	        // Get the views to bind to
	        SpeakerItemViews views = new SpeakerItemViews();
	        views.headerView = view.findViewById(R.id.header);
	        views.headerTextView = (TextView) view.findViewById(R.id.header_text);
	        views.dividerView = view.findViewById(R.id.session_divider);
	        views.nameView = (TextView) view.findViewById(R.id.speaker_name);
	        view.setTag(views);
	    }
	    
    }
    final static class PinnedHeaderCache {
        public TextView titleView;
        public ColorStateList textColor;
        public Drawable background;
    }
    
    public static final class SpeakerItemViews {
        public ImageView imageView;
		View headerView;
        TextView headerTextView;
        View dividerView;
        TextView nameView;
        CheckBox starButton;
        
    }
    
    private final class MyCursorAdapter extends BaseAdapter
	    implements SectionIndexer, OnScrollListener, PinnedHeaderListView.PinnedHeaderAdapter {

    	private AlphabetIndexer mIndexer;
    	private boolean mDisplaySectionHeaders = true;
	
		private final Context mContext;
		private final Cursor myCursor;
        public MyCursorAdapter(Context context, Cursor cursor) {
            super(context,cursor);
            this.myCursor=cursor;
            this.mContext = context;
            mIndexer = new AlphabetIndexer(cursor, cursor.getColumnIndex(DBAdapter.KEY_WORD), "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
        }

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
		    if (!myCursor.moveToPosition(position)) {
		        throw new IllegalStateException("couldn't move cursor to position " + position);
		    }
		    boolean newView;
		    View v;
		    if (convertView == null || convertView.getTag() == null) {
		        newView = true;
		        v = newView(mContext,myCursor, parent);
		    } else {
		        newView = false;
		        v = convertView;
		    }
		    bindView(v, mContext, myCursor);
		    bindSectionHeader(v, position, mDisplaySectionHeaders);
		    return v;
		}
		
        /** {@inheritDoc} */
        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View v = getLayoutInflater().inflate(R.layout.list_item_speaker, parent, false);
			findAndCacheViews(v);
			return v;
        }

        /** {@inheritDoc} */
        @Override
        public void bindView(View view, Context context, Cursor cursor) {
        	SpeakerItemViews views = (SpeakerItemViews) view.getTag();
            views.nameView.setText(cursor.getString(cursor.getColumnIndex(DBAdapter.KEY_WORD)));
        	//views.nameView.setText("AA");
        	views.nameView.setTextColor(Color.WHITE);
            ///set click  method here
            views.nameView.setClickable(true);
            views.nameView.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    Intent myIntent = new Intent(view.getContext(), Detail.class);
                   startActivityForResult(myIntent, 0);
                }
            });
        }

		private void bindSectionHeader(View view, int position, boolean displaySectionHeaders) {
			SpeakerItemViews views = (SpeakerItemViews) view.getTag();
		    if (!displaySectionHeaders) {
		    	views.headerView.setVisibility(View.GONE);
		    	views.dividerView.setVisibility(position == 0 ? View.GONE : View.VISIBLE);
		    } else {
		        final int section = getSectionForPosition(position);
		        if (getPositionForSection(section) == position) {
		            String title = (String) mIndexer.getSections()[section];
		            views.headerTextView.setText(title);
			    	views.headerView.setVisibility(View.VISIBLE);
			    	views.dividerView.setVisibility(View.GONE);
		        } else {
		        	views.headerView.setVisibility(View.GONE);
			    	views.dividerView.setVisibility(View.VISIBLE);
		        }
		
		        // move the divider for the last item in a section
		        if (getPositionForSection(section + 1) - 1 == position) {
			    	views.dividerView.setVisibility(View.GONE);
		        } else {
			    	views.dividerView.setVisibility(View.VISIBLE);
		        }
		    }
		}
	
		@Override
		public void changeCursor(Cursor cursor) {
			super.changeCursor(myCursor);
			
			updateIndexer(myCursor);
		}
		
		private void updateIndexer(Cursor cursor) {
			if (cursor == null) {
				mIndexer = null;
				return;
			}

			
		}

		@Override
		public int getPositionForSection(int section) {
			final Cursor cursor = getCursor();
			if (cursor == null || cursor.isClosed()) {
				return -1;
			}
			
			return mIndexer.getPositionForSection(section);
		}

		@Override
		public int getSectionForPosition(int position) {
			final Cursor cursor = getCursor();
			if (cursor == null || cursor.isClosed()) {
				return -1;
			}
			
			return mIndexer.getSectionForPosition(position);
		}

		@Override
		public Object[] getSections() {
			final Cursor cursor = getCursor();
			if (cursor == null || cursor.isClosed()) {
		        return new String[] { " " };
			}
			
			return mIndexer.getSections();
		}
          
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
		        int totalItemCount) {
		    if (view instanceof PinnedHeaderListView) {
		        ((PinnedHeaderListView) view).configureHeaderView(firstVisibleItem);
		    }
		}
		
		public void onScrollStateChanged(AbsListView view, int scrollState) {
		}
	
		/**
		 * Computes the state of the pinned header.  It can be invisible, fully
		 * visible or partially pushed up out of the view.
		 */
		public int getPinnedHeaderState(int position) {
			final Cursor cursor = getCursor();;
		    if (mIndexer == null || cursor == null || cursor.getCount() == 0) {
		        return PINNED_HEADER_GONE;
		    }
		
		    if (position < 0) {
		        return PINNED_HEADER_GONE;
		    }
		
		    // The header should get pushed up if the top item shown
		    // is the last item in a section for a particular letter.
		    int section = getSectionForPosition(position);
		    int nextSectionPosition = getPositionForSection(section + 1);
		    if (nextSectionPosition != -1 && position == nextSectionPosition - 1) {
		        return PINNED_HEADER_PUSHED_UP;
		    }
		
		    return PINNED_HEADER_VISIBLE;
		}
	
		/**
		 * Configures the pinned header by setting the appropriate text label
		 * and also adjusting color if necessary.  The color needs to be
		 * adjusted when the pinned header is being pushed up from the view.
		 */
		public void configurePinnedHeader(View header, int position, int alpha) {
		    PinnedHeaderCache cache = (PinnedHeaderCache) header.getTag();
	
		    if (cache == null) {
		        cache = new PinnedHeaderCache();
		        cache.titleView = (TextView) header.findViewById(R.id.header_text);
		        cache.textColor = cache.titleView.getTextColors();
		        cache.background = header.getBackground();
		        header.setTag(cache);
		    }
		
		    int section = getSectionForPosition(position);
		    
		    if (section != -1) {
			    String title = (String) mIndexer.getSections()[section];
			    cache.titleView.setText(title);
			
			    if (alpha == 255) {
			        // Opaque: use the default background, and the original text color
			        header.setBackgroundDrawable(cache.background);
			        cache.titleView.setTextColor(cache.textColor);
			    } else {
			        // Faded: use a solid color approximation of the background, and
			        // a translucent text color
			    	//final int diffAlpha = 255 - alpha;
			    	//final int red = Color.red(mPinnedHeaderBackgroundColor);
			    	//final int diffRed = 255 - red;
			    	//final int green = Color.green(mPinnedHeaderBackgroundColor);
			    	//final int diffGreen = 255 - green;
			    	//final int blue = Color.blue(mPinnedHeaderBackgroundColor);
			    	//final int diffBlue = 255 - blue;
			        //header.setBackgroundColor(Color.rgb(
			        //		red + (diffRed * diffAlpha / 255),
			        //		green + (diffGreen * diffAlpha / 255),
			        //		blue + (diffBlue * diffAlpha / 255)));
			
			        //int textColor = cache.textColor.getDefaultColor();
			       // cache.titleView.setTextColor(Color.argb(alpha,
			        //        Color.red(textColor), Color.green(textColor), Color.blue(textColor)));
			    }
		    }
		}

    }


}